const { request } = require('./request')
const getFormDataParams = require('../utils/getFormDataParams')
function getOssAccesstoken(data) {
    return request('POST', '/zeus/util/v1/attachment/sts/credentials', data)
}

const ossUpload = async ({ type = 'operation', fileName = 'file', filePath }) => {
    // profile_avatar - 头像，medical_examination - 健康证明，skill_certificate - 技能证书，identity_card - 身份证，identity_card - 身份证
    // style_img - 工作风采照片 style_video - 工作风采视频 operation - 运营图片 goods - 商品图片

    if (error('fileName', fileName)) return
    if (error('filePath', filePath)) return
    let qurey = await getOssAccesstoken({
        resource_abbr: type,
        resource_path: [fileName]
    })

    let formData = await getFormDataParams(qurey.Credentials.AccessKeyId, qurey.Credentials.AccessKeySecret, qurey.Credentials.SecurityToken)
    return new Promise((resolve, reject) => {
        const key = qurey.ResourcePath[0];
        uni.uploadFile({
            url: qurey.Domain, // 开发者服务器的URL。
            filePath: filePath,
            name: 'file', // 必须填file。
            formData: {
                ...formData,
                key,
            },
            success: (res) => {
                console.log(res)
                if (res.statusCode === 204) {
                    resolve(qurey.StorePath[0])
                }else{
                    reject(res)
                }
            },
            fail: err => {
                reject(err)
            }
        });
    })
}

function error(name, val) {
    if (!val) {
        Promise.reject(new Error(`${name} Can not be empty`))
        return true
    }
    return false
}
module.exports = {
    ossUpload
};